package cn.cuilan.secondkill.redis;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Service
public class RedisMonitor {

    private final static Logger logger = LoggerFactory.getLogger(RedisMonitor.class);

    private final static String PRE_MONITOR_KEY = "redis:monitor:";

    private JedisTemplate jedisTemplate;

    private int failCount = 0;

    @Autowired
    public RedisMonitor(JedisTemplate jedisTemplate) {
        this.jedisTemplate = jedisTemplate;
    }

    // 监控redis健康状态
    public void monitorRedis(String node) {
        String hostAddress = getHostAddress();
        String monitorKey = PRE_MONITOR_KEY + node + ":" + hostAddress;
        String errorMessage = "";
        try {
            boolean health = jedisTemplate.execute(jedis -> {
                String result = jedis.get(monitorKey);
                jedis.set(monitorKey, "1");
                if (StringUtils.isBlank(result)) {
                    // 30分钟过期时间
                    jedis.expire(monitorKey, 30 * 60);
                }
                result = jedis.get(monitorKey);
                return "1".equals(result);
            });
            failCount = health ? 0 : failCount + 1;
        } catch (Exception e) {
            // 发生异常
            failCount++;
            // 获取异常信息
            errorMessage = e.getMessage();
        }

        if (failCount > 5) {
            logger.error("检测到 redis 出现异常，IP：[{}]，异常信息：{}", hostAddress, errorMessage);
        } else {
            logger.info("redis 状态正常!");
        }
    }

    // 获取IP地址
    private String getHostAddress() {
        String hostName = "";
        try {
            hostName = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return hostName;
    }

}
